﻿using System;
using System.Collections.Generic;
using System.Linq;
using DevFramework.Core.DataAccess.NHibernate;
using DevFramework.DataLayer.Abstract;
using DevFramework.DataLayer.Concrete.NHibernate.Helper;
using DevFramework.Entities.Concrete;
using DevFramework.Entities.ComplexType;
using DevFramework.Entities.Concrete;
using NHibernate;
using NHibernate.Linq;

namespace DevFramework.DataLayer.Concrete.NHibernate
{
    public class NhProductDal : NhEntityRepositoryBase<Product>, IProductDal
    {
        private readonly NHibernateHelper _helper;

        public NhProductDal(NHibernateHelper helper)
            : base(helper)
        {
            _helper = helper;
        }

        public List<ProductDetail> GetWithCategory()
        {
            using (var session = _helper.OpenSession())
            {
                var result = from p in session.Query<Product>()
                             join c in session.Query<Category>()
                                 on p.CategoryId equals c.CategoryId
                             select new ProductDetail
                             {
                                 ProductId = p.ProductId,
                                 ProductName = p.ProductName,
                                 QuantityPerUnit = p.QuantityPerUnit,
                                 UnitPrice = p.UnitPrice,
                                 UnitsInStock = p.UnitsInStock,
                                 CategoryName = c.CategoryName
                             };

                return result.ToList();
            }
        }

        public List<Product> GetWithSp(int unitInStock)
        {
            using (var session = _helper.OpenSession())
            {
                return session.CreateSQLQuery("exec UrunleriGetir :adet")
                    .AddEntity(typeof(Product))
                    .SetParameter("adet", unitInStock)
                    .List<Product>().ToList();
            }
        }

        public void UpdateDate()
        {
            using (var session = _helper.OpenSession())
            {
                using (var transaction = session.BeginTransaction())
                {
                    session.CreateSQLQuery("exec TarihGuncelle").ExecuteUpdate();
                    transaction.Commit();
                }
            }
        }

        public List<Product> Search(Func<Product, bool> deleg)
        {
            using (var session = _helper.OpenSession())
            {
                return session.Query<Product>().Where(deleg).ToList();
            }
        }
    }
}
